<template>
  <div class="header-search">
    <i class="iconfont iconsearch" @click.stop="click"></i>
    <input
      ref="searchInput"
      :class="{ show: show }"
      v-model="searchValue"
      type="text"
      @click.stop=""
      @keyup.enter="search"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, Ref, watch } from "vue";
import { useRouter } from "vue-router";
export default defineComponent({
  name: "header-search",
  setup() {
    const searchValue: Ref<any> = ref("");
    const show: Ref<boolean> = ref(false);
    const searchInput: Ref<any> = ref(null);
    const router = useRouter();
    watch(
      () => show.value,
      (value, prev) => {
        if (value) {
          document.body.addEventListener("click", close);
        } else {
          document.body.removeEventListener("click", close);
        }
      }
    );

    const close = () => {
      searchInput && (searchInput as any).blur();
      show.value = false;
    };

    const search = () => {
      router.push({ name: "search", params: { words: searchValue.value } });
    };

    const click = () => {
      searchValue.value = "";
      show.value = !show.value;
      if (show.value) {
        searchInput && (searchInput as any).focus();
      }
    };

    return { search, searchValue, show,click };
  },
});
</script>

<style lang="less" scoped>
.header-search {
  display: inline-block;
  position: relative;
  i {
    font-size: 18px;
    position: relative;
    top: 3px;
  }
  input {
    border: none;
    outline: none;
    overflow: hidden;
    background: transparent;
    height: 30px;
    width: 0;
    transition: 0.2s all;
    &.show {
      width: 200px;
      margin-left: 10px;
    }
    &:focus {
      border-bottom: 1px solid #8fd0cc;
    }
  }
}
</style>